package com.yanqingshan.platform.module.sys.controller;

import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.yanqingshan.platform.common.constant.AppConstant;
import com.yanqingshan.platform.common.core.domain.PageQuery;
import com.yanqingshan.platform.common.core.domain.R;
import com.yanqingshan.platform.module.sys.convert.SysRoleConvert;
import com.yanqingshan.platform.module.sys.model.domain.SysRole;
import com.yanqingshan.platform.module.sys.model.vo.SysRoleReqVO;
import com.yanqingshan.platform.module.sys.service.SysRoleResourceService;
import com.yanqingshan.platform.module.sys.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * 功能描述:系统角色前端控制器
 *
 * @author yanqs
 * @since 2023-05-15
 */
@Api(tags = "系统角色")
@ApiSupport(order = 3)
@RestController
@RequestMapping(AppConstant.APPLICATION_SYSTEM + "/role")
public class SysRoleController {

    @Resource
    private SysRoleService sysRoleService;

    @Resource
    private SysRoleResourceService sysRoleResourceService;

    @ApiOperationSupport(order = 1)
    @ApiOperation("创建角色")
    @PostMapping("/create")
    public R createRole(@Valid @RequestBody SysRoleReqVO param) {
        SysRole sysRole = SysRoleConvert.INSTANCE.convert(param);
        return R.status(sysRoleService.save(sysRole));
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation("更新角色")
    @PutMapping("/update")
    public R updateRole(@Valid @RequestBody SysRoleReqVO param) {
        if (Objects.isNull(param.getId())) {
            return R.failed("参数错误");
        }
        SysRole sysRole = sysRoleService.getById(param.getId());
        if (Objects.isNull(sysRole)) {
            return R.failed("角色不存在");
        }
        sysRole = SysRoleConvert.INSTANCE.convert(param);
        return R.status(sysRoleService.updateById(sysRole));
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation("删除角色")
    @DeleteMapping("/{id}")
    public R delRole(@PathVariable Long id) {
        return R.status(sysRoleService.removeById(id));
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation("角色分页")
    @GetMapping("/page")
    public R pageCustom(SysRoleReqVO param, PageQuery query) {
        return R.ok(sysRoleService.pageCustom(param, query));
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation("角色分配资源")
    @PostMapping("/grant-resource")
    public R grantResource(@RequestParam Long roleId, @RequestParam List<Long> ids) {
        Assert.notNull(roleId, "角色 ID 不能为空");
        Assert.notNull(ids, "资源 IDs 不能为空");
        sysRoleResourceService.grantResource(roleId, ids);
        return R.ok();
    }


}
